package com.zhangtai.modules.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangtai.common.annotation.SysAuthorityLog;
import com.zhangtai.exception.QwMsg;
import com.zhangtai.modules.constVo.EmployeeConst;
import com.zhangtai.modules.constVo.NoticeConst;
import com.zhangtai.modules.constVo.SalaryConst;
import com.zhangtai.modules.constVo.TodoConst;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.*;
//import com.zhangtai.modules.dao.ssqlDao.JobDaoMssql;
import com.zhangtai.modules.dto.*;
import com.zhangtai.modules.entity.common.ContractUrlEntity;
import com.zhangtai.modules.entity.common.ImgUrlEntity;
import com.zhangtai.modules.entity.common.OrgEntity;
import com.zhangtai.modules.entity.employee.*;
import com.zhangtai.modules.entity.salary.OrgSystemEntity;
import com.zhangtai.modules.entity.salary.SalaryChangeEntity;
import com.zhangtai.modules.entity.salary.SalaryDistributionEntity;
import com.zhangtai.modules.entity.system.AuthorityLogEntity;
import com.zhangtai.modules.service.baseFromMssql.BaseMssqlServiceImpl;
import com.zhangtai.modules.service.common.ContractUrlService;
import com.zhangtai.modules.service.common.ImgUrlService;
import com.zhangtai.modules.service.employee.*;
import com.zhangtai.modules.service.salary.SalaryDistributionService;
import com.zhangtai.modules.vo.*;
import com.zhangtai.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Api(tags="新员工录入接口")
@RestController
@RequestMapping("hrEvent")
@Slf4j
public class HrEventController {

    @Autowired
    private EmployeeInfoService employeeInfoService;

    @Autowired
    private EmployeeInorgnameService employeeInorgnameService;
    @Autowired
    private EmployessSocietyexperienceService employessSocietyexperienceService;
    @Autowired
    private FamilyMemberService familyMemberService;

    @Autowired
    private ImgUrlService imgUrlService;
    @Autowired
    private ImgUrlDao imgUrlDao;

    @Autowired
    private LoginController loginController;
    @Autowired
    private EmployeeBpmService employeeBpmService;

    @Autowired
    private BaseMssqlServiceImpl jobService;

    @Autowired
    private EmployeeInfoDao employeeInfoDao;

    @Autowired
    private EmployeeEducationService employeeEducationService;
    @Autowired
    private EmployerCompanyService employerCompanyService;
//    @Autowired
//    private JobDaoMssql jobDaoMssql;
    @Autowired
    private QwMsg qwMsg;
    @Autowired
    private JobController jobController;
    @Autowired
    private NoticeController noticeController;
    @Autowired
    private ContractUrlDao contractUrlDao;

    @Autowired
    private AuthorityLogDao authorityLogDao;
    @Autowired
    private RelativeRecordsService relativeRecordsService;
    @Autowired
    private RelativeRecordsDao relativeRecordsDao;

    @Autowired
    private EmployeeRecruitmentService employeeRecruitmentService;



/*
    @PostMapping("/list")
    @ApiOperation(value="招聘台账列表，查询所有员工")
    @PreAuthorize("hasAuthority('emp:ygxx:get')")
    public R<PageResult<EmployeeInfoDto>> queryPage(@RequestBody @Valid EmployeeListDto employeeListDto,
                                                    HttpServletRequest request) throws  Exception{
//        log.info("employeeListDto:{}",employeeListDto);

        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        List<Long> selectOrg = null;
        List<Long> selectUnit = null;
        List<Long> selectJob = null;
        //null未查询，size为0查询结果为空
        if(!StringUtils.isEmpty(employeeListDto.getOrgname())){
            selectOrg = jobDaoMssql.findOrgByName(employeeListDto.getOrgname());
            if(selectOrg==null){
                selectOrg = new ArrayList<>();
            }
        }
        if(!StringUtils.isEmpty(employeeListDto.getUnitname())){
            selectUnit = jobDaoMssql.findOrgByName(employeeListDto.getUnitname());
            if(selectUnit==null){
                selectUnit = new ArrayList<>();
            }
        }
        if(!StringUtils.isEmpty(employeeListDto.getJobname())){
            selectJob = jobDaoMssql.findJobIdByName(employeeListDto.getJobname());
            if(selectJob==null){
                selectJob = new ArrayList<>();
            }
        }

        R u = loginController.getUserInfo(request);
        JSONObject user = (JSONObject) u.getData();
        String code = user.getString("usercode");
        //当前日期
//        String date= DateUtils.format(new Date(),"yyyy-MM-dd")+" 23:59:59";
//        PageResult<EmployeeInfoEntity> pageResult = employeeInfoService.queryPage(employeeOid,name,orgname,unitname,jobname,keyword, status,isReinstate,isEntryStatus,pageNum,pageSize,orgIds);
        PageResult<EmployeeInfoEntity> pageResult = employeeInfoService.queryPage(employeeListDto.getEmployeeOid(),employeeListDto.getName(),
                selectOrg,selectUnit,selectJob,
                employeeListDto.getStatus(),employeeListDto.getIsReinstate(),employeeListDto.getIsEntryStatus(),
                employeeListDto.getPageNum(),employeeListDto.getPageSize(),orgIds,employeeListDto.getSocialTrainee(),
                employeeListDto.getIsOffer(),employeeListDto.getIsSendContract(),code);
        List<EmployeeInfoEntity> list = pageResult.getList();
        ArrayList<EmployeeInfoDto> infoDtoList = new ArrayList<>();

        for (EmployeeInfoEntity infoEntity : list) {
            Long orgId = infoEntity.getOrgId();
            Long unitId = infoEntity.getUnitId();
            Long jobId = infoEntity.getJobId();
            Long jobLevelId = infoEntity.getJobLevelId();

//            根据id去换缓存中获取组织名称
            String orgName = jobController.getOrgNameById(orgId);
            String unitName = jobController.getOrgNameById(unitId);
            //根据id去换缓存中获取岗位名称
            String jobName = jobController.getJobName(jobId);

            //根据id去换缓存中获取职级名称
            String jobLevelName = jobController.getJobLevelNameById(jobLevelId);


            EmployeeInfoDto employeeInfoDto = BeanUtilsMabach.doToDto(infoEntity, EmployeeInfoDto.class);


            employeeInfoDto.setOrgname(orgName);
            employeeInfoDto.setUnitname(unitName);
            employeeInfoDto.setJobname(jobName);
            employeeInfoDto.setJobLevel(jobLevelName);

            //查询修改入职记录
            if (employeeListDto.getIsShowAuthorityLog()) {
                List<AuthorityLogEntity> authorityLogEntity = authorityLogDao.selectList(new QueryWrapper<AuthorityLogEntity>()
                        .eq("is_delete", "0")
                        .eq("oid", infoEntity.getOid())
                        .eq("type", 1)
                        .orderByDesc("update_time"));
                if(!CollectionUtils.isEmpty(authorityLogEntity)){
                    AuthorityLogEntity entity =authorityLogEntity.get(0);
                    employeeInfoDto.setUpdateEntryStr("修改人：" +entity.getUpdateUserName()+"，修改前入职日期:"+entity.getOldData());
                }

            }
            infoDtoList.add(employeeInfoDto);

        }
        PageResult<EmployeeInfoDto> result = new PageResult<>();
        result.setList(infoDtoList);
        result.setCurrPage(pageResult.getCurrPage());
        result.setPageSize(pageResult.getPageSize());
        result.setTotalCount(pageResult.getTotalCount());
        result.setTotalPage(pageResult.getTotalPage());

        return R.ok(result);


    }*/


    @PostMapping("/list")
    @ApiOperation(value="招聘台账列表，查询所有员工")
    @PreAuthorize("hasAuthority('emp:ygxx:get')")
    public R<PageResult<EmployeeInfoDto>> queryPage(@RequestBody @Valid EmployeeListDto employeeListDto,
                                                    HttpServletRequest request) throws  Exception{
//        log.info("employeeListDto:{}",employeeListDto);

        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        List<Long> selectOrg = null;
        List<Long> selectUnit = null;
        List<Long> selectJob = null;
        //null未查询，size为0查询结果为空
        if(!StringUtils.isEmpty(employeeListDto.getOrgname())){
//            selectOrg = jobDaoMssql.findOrgByName(employeeListDto.getOrgname());
            if(selectOrg==null){
                selectOrg = new ArrayList<>();
            }
        }
        if(!StringUtils.isEmpty(employeeListDto.getUnitname())){
//            selectUnit = jobDaoMssql.findOrgByName(employeeListDto.getUnitname());
            if(selectUnit==null){
                selectUnit = new ArrayList<>();
            }
        }
        if(!StringUtils.isEmpty(employeeListDto.getJobname())){
//            selectJob = jobDaoMssql.findJobIdByName(employeeListDto.getJobname());
            if(selectJob==null){
                selectJob = new ArrayList<>();
            }
        }

        R u = loginController.getUserInfo(request);
        JSONObject user = (JSONObject) u.getData();
        String code = user.getString("usercode");
        PageResult<EmployeeRecruitmentEntity> pageResult = employeeRecruitmentService.queryPage(employeeListDto.getName(),
                selectOrg, selectUnit, selectJob,
                employeeListDto.getStatus(),  employeeListDto.getIsEntryStatus(),
                employeeListDto.getPageNum(), employeeListDto.getPageSize(), orgIds, employeeListDto.getSocialTrainee(),
                employeeListDto.getIsOffer(), employeeListDto.getIsSendContract(), code);


        List<EmployeeRecruitmentEntity> list = pageResult.getList();
        ArrayList<EmployeeInfoDto> infoDtoList = new ArrayList<>();

        for (EmployeeRecruitmentEntity infoEntity : list) {

            EmployeeInfoDto employeeInfoDto = BeanUtilsMabach.doToDto(infoEntity, EmployeeInfoDto.class);

            // 入职办理缺少员工主表数据，在这里补充 czw 2021-04-19
            EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(infoEntity.getOid());
            if(!ObjectUtils.isEmpty(employeeInfoEntity)){
                employeeInfoDto = BeanUtilsMabach.doToDto(employeeInfoEntity, EmployeeInfoDto.class);
            }

            Long orgId = infoEntity.getOrgId();
            Long unitId = infoEntity.getUnitId();
            Long jobId = infoEntity.getJobId();
            Long jobLevelId = infoEntity.getJobLevelId();

//            根据id去换缓存中获取组织名称
            String orgName = jobController.getOrgNameById(orgId);
            String unitName = jobController.getOrgNameById(unitId);
            //根据id去换缓存中获取岗位名称
            String jobName = jobController.getJobName(jobId);

            //根据id去换缓存中获取职级名称
            String jobLevelName = jobController.getJobLevelNameById(jobLevelId);

            employeeInfoDto.setOrgname(orgName);
            employeeInfoDto.setUnitname(unitName);
            employeeInfoDto.setJobname(jobName);
            employeeInfoDto.setJobLevel(jobLevelName);

            //查询修改入职记录
            if (employeeListDto.getIsShowAuthorityLog()) {
                List<AuthorityLogEntity> authorityLogEntity = authorityLogDao.selectList(new QueryWrapper<AuthorityLogEntity>()
                        .eq("is_delete", "0")
                        .eq("oid", infoEntity.getOid())
                        .eq("type", 1)
                        .orderByDesc("update_time"));
                if(!CollectionUtils.isEmpty(authorityLogEntity)){
                    AuthorityLogEntity entity =authorityLogEntity.get(0);
                    employeeInfoDto.setUpdateEntryStr("修改人：" +entity.getUpdateUserName()+"，修改前入职日期:"+entity.getOldData());
                }

            }
            infoDtoList.add(employeeInfoDto);

        }
        PageResult<EmployeeInfoDto> result = new PageResult<>();
        result.setList(infoDtoList);
        result.setCurrPage(pageResult.getCurrPage());
        result.setPageSize(pageResult.getPageSize());
        result.setTotalCount(pageResult.getTotalCount());
        result.setTotalPage(pageResult.getTotalPage());

        return R.ok(result);


    }






    @GetMapping("/getEmployeeById/{id}")
    @ApiOperation(value="根据员工id获取详情(从现有库中查询)")
    @PreAuthorize("hasAuthority('emp:ygxx:get')")
    // @SysLog(value ="测试[{{id}}]备份",operationType = OperationType.SELECT)
    public R<EmployeeInfoDto> findEmployeeByOid(@PathVariable("id") Long id) {
        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(id);
        if (ObjectUtils.isEmpty(employeeInfoEntity)){
            return R.ok();
        }
        Long oid = employeeInfoEntity.getOid();

        List<EmployeeEducationEntity> educationEntities = employeeEducationService.findEmployeeEducationListByOid(oid);
        List<EmployeeInorgnameEntity> inorgnameEntityList = employeeInorgnameService.getByEmpId(oid);
//        log.info("政治面貌:{}",inorgnameEntityList);
        List<EmployessSocietyexperienceEntity> societyexperienceEntities = employessSocietyexperienceService.getByEmpId(oid);
        //查询员工合同记录
        List<ContractUrlEntity> contractList= contractUrlDao.selectList(new QueryWrapper<ContractUrlEntity>().eq("is_delete",0).eq("id_card",employeeInfoEntity.getIdcard()));
        List<FamilyMemberEntity> familyMemberEntities = familyMemberService.getListByEmpId(oid);
//        亲属报备
        List<RelativeRecordsEntity> relativeRecordsEntities = relativeRecordsDao.selectList(new QueryWrapper<RelativeRecordsEntity>().eq("oid", oid).eq("is_delete", 0));

        EmployeeInfoDto employeeInfoDto = BeanUtilsMabach.doToDto(employeeInfoEntity, EmployeeInfoDto.class);
        employeeInfoDto.setEmployeeEducation(educationEntities);
        employeeInfoDto.setEmployeeInorgname(inorgnameEntityList);
        employeeInfoDto.setFamilyMember(familyMemberEntities);
        employeeInfoDto.setEmployeeSociety(societyexperienceEntities);
        employeeInfoDto.setContractList(contractList);
        employeeInfoDto.setRelativeRecordsEntities(relativeRecordsEntities);


        getImg(oid, employeeInfoDto); //封装图片


        /**
         * 根据各种id查询名称
         */
        Long unitId = employeeInfoEntity.getUnitId();
        Long orgId = employeeInfoEntity.getOrgId();
        Long jobId = employeeInfoEntity.getJobId();

        Long jobSystemId = employeeInfoEntity.getJobSystemId();
        Long lineId = employeeInfoEntity.getLineId();



        Long jobLevelId = employeeInfoEntity.getJobLevelId();
        JobDto jobDto = jobService.findJobById(jobId);



        JobLevelDto jobLevelById = jobService.findJobLevelById(jobLevelId);
        log.info("JobLevelDto:{}",jobLevelById);
        if (!ObjectUtils.isEmpty(jobLevelById)){
            employeeInfoDto.setJobLevel(jobLevelById.getName());
        }




        OrgSystemEntity systemById = jobService.findSystemById(jobSystemId);
//        log.info("OrgSystemEntity:{}",jobLevelById);
        if (!ObjectUtils.isEmpty(systemById)){
            employeeInfoDto.setJobSystem(systemById.getName());
        }
        OrgSystemEntity lineById = jobService.findLineById(lineId);
//        log.info("OrgSystemEntity:{}",jobLevelById);
        if (!ObjectUtils.isEmpty(lineById)){
            employeeInfoDto.setLine(lineById.getName());
        }
        OrgEntity org = jobService.findOrgById(orgId);
        if (!ObjectUtils.isEmpty(org)){
            employeeInfoDto.setOrgname(org.getName());
        }

        OrgEntity unit = jobService.findOrgById(unitId);
        if (!ObjectUtils.isEmpty(unit)){
            employeeInfoDto.setUnitname(unit.getName());
        }

        JobDto jobByJobId = jobService.findJobById(jobId);
//        log.info("JobDto:{}",jobLevelById);
        if (!ObjectUtils.isEmpty(jobByJobId)){
            employeeInfoDto.setJobname(jobByJobId.getCname());
        }
        if (!ObjectUtils.isEmpty(jobDto)){
            employeeInfoDto.setJobname(jobDto.getCname());
        }
        Long employerCompanyId = employeeInfoEntity.getEmployerCompanyId();
        EmployerCompanyEntity byIdE = employerCompanyService.getByIdE(employerCompanyId);
        if (!ObjectUtils.isEmpty(byIdE)){
            //        封装甲方单位
            employeeInfoDto.setEmployerCompany(byIdE.getName());
        }


//        封装复职员工信息
        Integer isReinstate = employeeInfoEntity.getIsReinstate(); //0:新员工，1：复职员工，2：旧员工,3:离职超过一年
        Integer i=1;
        Integer k=3;
        if (i.equals(isReinstate)||k.equals(isReinstate)){
            EmployeeBpmEntity employeeBpmEntity = employeeBpmService.getByIdE(oid);
            if (!ObjectUtils.isEmpty(employeeBpmEntity)){
                OldEmployeeDto oldEmployeeDto = BeanUtilsMabach.doToDto(employeeBpmEntity, OldEmployeeDto.class);
                employeeInfoDto.setOldEmployeeDto(oldEmployeeDto);
            }
        }



        return R.ok(employeeInfoDto);
    }










    @PostMapping("/updateMainInfo")
    @ApiOperation(value="修改新员工主体信息")
    @SysAuthorityLog(value = "修改新员工主体信息")
    @Transactional
    @PreAuthorize("hasAuthority('emp:ygxx:update')")
    public R updateMainInfo(@RequestBody EmployeeInfoUpdateVo employeeInfoUpdateVo,HttpServletRequest request)throws  Exception{
        Boolean flag=false;
//        JSONObject data = loginController.getUserInfo(request).getData();
//        String name = data.getString("name");
//        String usercode = data.getString("usercode");
        EmployeeInfoEntity employeeInfoEntity = BeanUtilsMabach.doToDto(employeeInfoUpdateVo, EmployeeInfoEntity.class);
        if(!ObjectUtils.isEmpty(employeeInfoUpdateVo.getNativeplace())){
            employeeInfoEntity.setNativeplace(employeeInfoUpdateVo.getNativeplace().toString());
        }
//        if(!ObjectUtils.isEmpty(employeeInfoUpdateVo.getNativeplaceProvince())){
//            employeeInfoEntity.setNativeplaceProvince(employeeInfoUpdateVo.getNativeplaceProvince().toString());
//        }
        String idcard = employeeInfoUpdateVo.getIdcard().trim();
        employeeInfoEntity.setIdcard(idcard);
        String mobile = employeeInfoUpdateVo.getMobile().trim();
        employeeInfoEntity.setMobile(mobile);
        //判断是否为有该公司的权限
//        R checkR = loginController.checkOrgPermission(request,employeeInfoEntity.getOrgId(),true);
//        if(!R.isOk.equals(checkR.getStatus())&&!isPrincipalUser(request,employeeInfoEntity.getOid())){
//            return checkR;
//        }
        employeeInfoEntity.setOperatetime(new Date());
        employeeInfoEntity.setUpdateTime(new Date());
        Long id = employeeInfoUpdateVo.getOid();

        //        封装图片
        updateImg( employeeInfoUpdateVo);

        Date hiredate = employeeInfoUpdateVo.getHiredate();
        if (hiredate!=null){
            Integer probationday = employeeInfoUpdateVo.getProbationday(); //试用期
            Date reguDate = DateUtils.addDateMonths(hiredate, probationday);
            employeeInfoEntity.setRegularDay(reguDate);
        }

        EmployeeBpmEntity employeeBpmEntity = BeanUtilsMabach.doToDto(employeeInfoEntity, EmployeeBpmEntity.class);

        employeeBpmEntity.setUpdateTime(new Date());
        employeeBpmService.updateByIdE(employeeBpmEntity);


//        setJoblevel2(employeeInfoUpdateVo, employeeInfoEntity); // 根据管理职级id是否为空设置岗位职级


        EmployeeInfoEntity employeeInfo = employeeInfoService.getByIdE(employeeBpmEntity.getOid());
        //查看是否是录用BPM审批中过且入职日期有变更
        if(!ObjectUtils.isEmpty(employeeInfo)&&EmployeeConst.EMPLOYEE_STATUS_PASSED.equals(employeeInfo.getStatus())
                &&!ObjectUtils.isEmpty(employeeInfo.getHiredate())
                &&!employeeInfo.getHiredate().equals(employeeInfoEntity.getHiredate())){
            //将之前的待办信息置为已读
            noticeController.updateNoticeTodo(employeeInfoEntity.getOid(),NoticeConst.TODO_TYPE_NEW_EMPLOYEE);
            //发送新的待办信息
            sendHireToDo(employeeInfoEntity);
        }
        employeeInfoService.updateByIdE(employeeInfoEntity);

        //修改招聘数据信息
        EmployeeInfoEntity entity1= employeeInfoService.getByIdE(employeeInfoEntity.getOid());
        if(!StringUtils.isEmpty(entity1.getRecruitmentId())){
            EmployeeRecruitmentEntity employeeRecruitmentEntity = BeanUtilsMabach.doToDto(employeeInfoEntity, EmployeeRecruitmentEntity.class);
            employeeRecruitmentEntity.setId(entity1.getRecruitmentId());
            employeeRecruitmentService.updateByIdE(employeeRecruitmentEntity);
        }
        flag=true;
        if (flag){
            return R.ok();
        }

        return R.error();
    }








    @GetMapping("/getEmployeeSalaryBpmById/{oid}")
    @ApiOperation(value="根据员工id查询新员工bpm审核")
    @PreAuthorize("hasAuthority('emp:ygxx:get')")
    public R<EmployeeBpmDto> getEmployeeSalaryBpmById(@PathVariable("oid") Long oid){
        EmployeeBpmEntity bpmEntity=employeeBpmService.getByIdE(oid);
        if (ObjectUtils.isEmpty(bpmEntity)){
            return R.error("根据员工id查询为空");
        }

        EmployeeBpmDto employeeBpmDto = BeanUtilsMabach.doToDto(bpmEntity, EmployeeBpmDto.class);

//        封装参数
        setArgs(bpmEntity, employeeBpmDto);


//        getBpmImg(employeeBpmDto); //封装附件


        return R.ok(employeeBpmDto);

    }

    @PostMapping("/updateEmployeeSalaryBpmById")
    @ApiOperation(value="修改新员工bpm审核表单")
    @SysAuthorityLog(value = "修改新员工bpm审核表单")
    @Transactional
    @PreAuthorize("hasAuthority('emp:ygxx:update')")
    public R updateEmployeeSalaryBpmById(@RequestBody @Valid  UpdateEmployeeBpmVo updateEmployeeBpmVo,HttpServletRequest request
    )throws Exception{
//        log.info("updateEmployeeBpmVo===========>>>>>>>>>>:{}",updateEmployeeBpmVo);
        Boolean flag=false;

        EmployeeBpmEntity employeeBpmEntity = BeanUtilsMabach.doToDto(updateEmployeeBpmVo, EmployeeBpmEntity.class);



        EmployeeInfoEntity employeeInfoEntity = BeanUtilsMabach.doToDto(updateEmployeeBpmVo, EmployeeInfoEntity.class);
        JSONObject data = loginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(data)){
            return R.error("请先登录");
        }


        setBpmImg(updateEmployeeBpmVo); //封装附件

        String name = data.getString("name");
        String usercode = data.getString("usercode");
        employeeBpmEntity.setApplyUserCode(usercode);
        employeeBpmEntity.setApplyName(name);
        employeeInfoEntity.setPrincipalUserCode(usercode);
        employeeInfoEntity.setPrincipal(name);
        employeeBpmEntity.setUpdateTime(new Date());
        employeeInfoEntity.setUpdateTime(new Date());
        employeeInfoService.updateByIdE(employeeInfoEntity);
        employeeBpmService.updateByIdE(employeeBpmEntity);





        flag=true;
        if (flag){
            return R.ok();
        }else {
            return R.error();
        }


    }



    public void sendHireToDo( EmployeeInfoEntity employeeInfo)  {
//        String dString = DateUtils.format(employeeInfo.getHiredate(), "yyyy-MM-dd");
//        String nowString = DateUtils.format(new Date(), "yyyy-MM-dd");
//        Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dString);
//        Date now = new SimpleDateFormat("yyyy-MM-dd").parse(nowString);
        //修改入职时间发送待入职信息
        String content = "您有一条入职流程需要处理：" + employeeInfo.getName();
        //发送企微信息以及入职待办通知
        qwMsg.sendNoticeMsg("入职待办",content, TodoConst.PRE_ENTRY, false, employeeInfo.getOid(), employeeInfo.getOid(), "入职", null, employeeInfo.getHiredate(),employeeInfo.getOrgId());
    }


    /**
     * 发送录用待办
     * @param employeeInfoEntity
     */
    private void sendNewEmployeeToDo(EmployeeInfoEntity employeeInfoEntity,String userCode){
        String content = "您有一条录用流程需要处理：" + employeeInfoEntity.getName();
        qwMsg.sendNoticeMsg("录用待办",content, TodoConst.PRE_HIRE, false, employeeInfoEntity.getOid(), employeeInfoEntity.getOid(), "录用", userCode, new Date(),null);
    }





    @GetMapping("/getEduByOid/{id}")
    @ApiOperation(value="根据员工id查询教育信息")
    public R getEduByOid(@PathVariable("id")Long id){

        List<EmployeeEducationEntity> employeeEducationListByOid = employeeEducationService.findEmployeeEducationListByOid(id);

        return R.ok(employeeEducationListByOid);
    }


    @GetMapping("/getRelativeRecords/{oid}")
    @ApiOperation(value="根据oid获取员工亲属报备信息")
    public R<List<RelativeRecordsEntity>> getRelativeRecords(@PathVariable("oid")Long oid,HttpServletRequest request)throws  Exception{

        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(oid);
        if(ObjectUtils.isEmpty(employeeInfoEntity)){
            return R.error("员工信息不存在");
        }
        List<RelativeRecordsEntity> relativeRecordsEntities = relativeRecordsDao.selectList(new QueryWrapper<RelativeRecordsEntity>().eq("oid", oid).eq("is_delete", 0));



        return R.ok(relativeRecordsEntities);
    }


    @PostMapping("/saveRelativeRecords")
    @ApiOperation(value="添加员工亲属报备信息")
    @SysAuthorityLog(value = "添加员工亲属报备信息")
    public R saveRelativeRecords(@RequestBody @Valid RelativeRecordsEntity relativeRecordsEntity,HttpServletRequest request)throws  Exception{

        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(relativeRecordsEntity.getOid());
        if(ObjectUtils.isEmpty(employeeInfoEntity)){
            return R.error("员工信息不存在");
        }


        R r = relativeRecordsService.saveE(relativeRecordsEntity);
        return r;
    }

    @PostMapping("/updateRelativeRecords")
    @ApiOperation(value="修改员工亲属报备信息")
    @SysAuthorityLog(value = "添加员工亲属报备信息")
    public R updateRelativeRecords(@RequestBody @Valid RelativeRecordsEntity relativeRecordsEntity,HttpServletRequest request)throws  Exception{

        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(relativeRecordsEntity.getOid());
        if(ObjectUtils.isEmpty(employeeInfoEntity)){
            return R.error("员工信息不存在");
        }


        R r = relativeRecordsService.updateByIdE(relativeRecordsEntity);
        return r;
    }

    @DeleteMapping("/deleteRelativeRecords/{id}")
    @ApiOperation(value="删除员工亲属报备信息")
    @SysAuthorityLog(value = "添加员工亲属报备信息")
    public R deleteRelativeRecords(@PathVariable("id")Long id)throws  Exception{


        R r = relativeRecordsService.removeOneById(id);
        return r;
    }

    @PostMapping("/saveEducationInfo")
    @ApiOperation(value="添加新员工教育信息")
    @SysAuthorityLog(value = "添加新员工教育信息")
    public R saveEducationInfo(@RequestBody @Valid EmployeeEducationVo employeeEducationVo,HttpServletRequest request)throws  Exception{
        EmployeeEducationEntity employeeEducationEntity = BeanUtilsMabach.doToDto(employeeEducationVo, EmployeeEducationEntity.class);
        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(employeeEducationEntity.getEmpoid());
        if(ObjectUtils.isEmpty(employeeInfoEntity)){
            return R.error("员工信息不存在");
        }
//        //判断是否为有该公司的权限
//        R checkR = loginController.checkOrgPermission(request,employeeInfoEntity.getOrgId(),true);
//        if(!R.isOk.equals(checkR.getStatus())&&!isPrincipalUser(request,employeeEducationEntity.getEmpoid())){
//            return checkR;
//        }
        employeeEducationEntity.setOperatetime(new Date());
        R r = employeeEducationService.saveE(employeeEducationEntity);
        return r;
    }

    @PostMapping("/updateEducationInfo")
    @ApiOperation(value="修改员工教育信息")
    @SysAuthorityLog(value = "修改员工教育信息")
    public R updateEducationInfo(@RequestBody @Valid EmployeeEducationUpdateVo employeeEducationVo,HttpServletRequest request)throws  Exception{
        EmployeeEducationEntity employeeEducationEntity = BeanUtilsMabach.doToDto(employeeEducationVo, EmployeeEducationEntity.class);

//        EmployeeInfoEntity employeeBpmEntity = employeeInfoService.getByIdE(employeeEducationEntity.getEmpoid());
        if(ObjectUtils.isEmpty(employeeEducationEntity)){
            return R.error("员工信息不存在");
        }
//        //判断是否为有该公司的权限
//        R checkR = loginController.checkOrgPermission(request,employeeBpmEntity.getOrgId(),true);
//        if(!R.isOk.equals(checkR.getStatus())&&!isPrincipalUser(request,employeeEducationEntity.getEmpoid())){
//            return checkR;
//        }
        employeeEducationEntity.setOperatetime(new Date());
        R r = employeeEducationService.updateByIdE(employeeEducationEntity);
        return r;
    }

    @GetMapping("/deleteEducation/{id}")
    @ApiOperation(value="删除员工教育信息")
    @SysAuthorityLog(value = "删除员工教育信息")
    public R deleteEducation(@PathVariable("id")  Long  id,HttpServletRequest request)throws Exception{
        EmployeeEducationEntity entity = employeeEducationService.getByIdE(id);
        if(ObjectUtils.isEmpty(entity)){
            return R.error("员工信息不存在！");
        }
//        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(entity.getEmpoid());
//        //判断是否为有该公司的权限
//        R checkR = loginController.checkOrgPermission(request,employeeInfoEntity.getOrgId(),true);
//        if(!R.isOk.equals(checkR.getStatus())&&!isPrincipalUser(request,entity.getEmpoid())){
//            return checkR;
//        }
        R r = employeeEducationService.removeOneById(id);
        return r;
    }

    @GetMapping("/getInorgInfo/{id}")
    @ApiOperation(value="获取员工id政治面貌")
    public R<List<EmployeeInorgnameEntity>> getInorgInfo(@PathVariable("id")  Long  id) {
        List<EmployeeInorgnameEntity> byEmpId = employeeInorgnameService.getByEmpId(id);
        return R.ok(byEmpId);
    }






    @PostMapping("/saveInorgInfo")
    @ApiOperation(value="添加新政治面貌信息")
    @SysAuthorityLog(value = "添加新政治面貌信息")
    public R saveInorg(@RequestBody @Valid EmployeeInorgnameVo employeeInorgnameVo){
        EmployeeInorgnameEntity employeeInorgnameEntity = BeanUtilsMabach.doToDto(employeeInorgnameVo, EmployeeInorgnameEntity.class);
        employeeInorgnameEntity.setOperatetime(new Date());
        R r = employeeInorgnameService.saveE(employeeInorgnameEntity);
//        log.info("入党：{}",employeeInorgnameVo);
        return r;
    }

    @PostMapping("/updateInorgInfo")
    @ApiOperation(value="修改新员工政治面貌信息")
    @SysAuthorityLog(value = "修改新员工政治面貌信息")
    public R updateInorg(@RequestBody @Valid EmployeeInorgnameUpdateVo employeeInorgnameUpdateVo){
        EmployeeInorgnameEntity employeeInorgnameEntity = BeanUtilsMabach.doToDto(employeeInorgnameUpdateVo, EmployeeInorgnameEntity.class);
        employeeInorgnameEntity.setOperatetime(new Date());
        R r = employeeInorgnameService.updateByIdE(employeeInorgnameEntity);
        return r;
    }

    @GetMapping("/deleteInorg/{id}")
    @ApiOperation(value="删除员工政治面貌信息")
    @SysAuthorityLog(value = "删除员工政治面貌信息")
    public R deleteInorg(@PathVariable("id")  String  id){

        R r = employeeInorgnameService.removeOneById(Long.valueOf(id));
        return r;
    }


    @GetMapping("/getSocietyInfo/{id}")
    @ApiOperation(value="根据员工id查询工作履历")
    public R<List<EmployessSocietyexperienceEntity>> getSocietyInfo(@PathVariable("id")  Long  id) {


        List<EmployessSocietyexperienceEntity> byEmpId = employessSocietyexperienceService.getByEmpId(id);
        return R.ok(byEmpId);
    }

    @PostMapping("/saveSociety")
    @ApiOperation(value="添加新员工作履历")
    @SysAuthorityLog(value = "添加新员工作履历")
    public R saveSociety(@RequestBody @Valid EmployessSocietyVo employessSocietyVo){
        Long empoid = employessSocietyVo.getEmpoid();
        EmployeeInfoEntity byIdE = employeeInfoService.getByIdE(empoid);
        if (ObjectUtils.isEmpty(byIdE)){
            return R.error("查不到该员工主体信息");
        }
        EmployessSocietyexperienceEntity employessSocietyexperienceEntity = BeanUtilsMabach.doToDto(employessSocietyVo, EmployessSocietyexperienceEntity.class);
        employessSocietyexperienceEntity.setOperatetime(new Date());
        R r = employessSocietyexperienceService.saveE(employessSocietyexperienceEntity);
        log.info("工作信息参数是：{}",employessSocietyVo);
        return r;
    }

    @PostMapping("/updateSociety")
    @ApiOperation(value="修改新员工作履历")
    @SysAuthorityLog(value = "修改新员工作履历")
    public R updateSociety(@RequestBody @Valid EmployessSocietyUpdateVo employessSocietyVo){

        EmployessSocietyexperienceEntity employessSocietyexperienceEntity = BeanUtilsMabach.doToDto(employessSocietyVo, EmployessSocietyexperienceEntity.class);
        employessSocietyexperienceEntity.setOperatetime(new Date());
        R r = employessSocietyexperienceService.updateByIdE(employessSocietyexperienceEntity);
        return r;
    }

    @GetMapping("/deleteSociety/{id}")
    @ApiOperation(value="删除员工工作履历")
    @SysAuthorityLog(value = "删除员工工作履历")
    public R deleteSociety(@PathVariable("id")  Long  id){

        R r = employessSocietyexperienceService.removeOneById(id);
        return r;
    }



    @GetMapping("/getFamilyListByOid/{id}")
    @ApiOperation(value="获取员工家庭信息")
    public R<List<FamilyMemberEntity>> getFamilyListByOid(@PathVariable("id")Long id){
        List<FamilyMemberEntity> familyMemberEntities = familyMemberService.getListByEmpId(id);
        return R.ok(familyMemberEntities);
    }
    @PostMapping("/saveFamily")
    @ApiOperation(value="添加新员工家庭联关系")
    @SysAuthorityLog(value = "添加新员工家庭联关系")
    public R saveFamily(@RequestBody @Valid FamilyMemberVo employessSocietyVo){
        FamilyMemberEntity employessSocietyexperienceEntity = BeanUtilsMabach.doToDto(employessSocietyVo, FamilyMemberEntity.class);
        employessSocietyexperienceEntity.setOperatetime(new Date());
        R r = familyMemberService.saveE(employessSocietyexperienceEntity);
        return r;
    }

    @PostMapping("/updateFamily")
    @ApiOperation(value="修改员工家庭联关系")
    @SysAuthorityLog(value = "修改员工家庭联关系")
    public R updateFamily(@RequestBody @Valid FamilyMemberUpdateVo employessSocietyVo){
//        log.info("参数为:{}",employessSocietyVo);
        FamilyMemberEntity employessSocietyexperienceEntity = BeanUtilsMabach.doToDto(employessSocietyVo, FamilyMemberEntity.class);
        employessSocietyexperienceEntity.setOperatetime(new Date());
        R r = familyMemberService.updateByIdE(employessSocietyexperienceEntity);
        return r;
    }

    @GetMapping("/deleteFamily/{id}")
    @ApiOperation(value="删除员工家庭成员信息")
    @SysAuthorityLog(value = "删除员工家庭成员信息")
    public R deleteFamily(@PathVariable("id")  Long  id){

        R r = familyMemberService.removeOneById(id);
        return r;
    }

    @GetMapping("/updateEmployeeInfoCodeByOid")
    @ApiOperation(value="根据oid修改员工工号")
    @SysAuthorityLog(value = "根据oid修改员工工号")
    public R updateEmployeeInfo(@RequestParam("oid")  String  oid,@RequestParam("code")  String  code){
        List<EmployeeInfoEntity>  employeeInfoEntityList=  employeeInfoDao.selectList(new QueryWrapper<EmployeeInfoEntity>().eq("code", code).eq("is_delete",0));
        if(!CollectionUtils.isEmpty(employeeInfoEntityList)){
            R.error("该工号已使用，请重新填写");
        }
        EmployeeInfoEntity employeeInfoEntity= employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("oid",oid).eq("is_delete",0));
        if(ObjectUtils.isEmpty(employeeInfoEntity)){
            R.error("未找到该员工");
        }
        employeeInfoEntity.setCode(code);
        employeeInfoDao.updateById(employeeInfoEntity);
        return R.ok();
    }



    private void setImg(@RequestBody EmployeeInfoVo employeeInfoVo, Long id) {
        //        上传原单位薪资流水
        List<String> oldSalaryRecordUrl = employeeInfoVo.getOldSalaryRecordUrl();
        if (!CollectionUtils.isEmpty(oldSalaryRecordUrl)){
            for (String s : oldSalaryRecordUrl) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setName("原公司工资流水");
                imgUrlEntity.setOid(id);
                imgUrlEntity.setType(1); //0:流水，1：头像
                imgUrlEntity.setCreateTime(new Date());
                imgUrlEntity.setUrl(s);
                imgUrlService.saveE(imgUrlEntity);
            }
        }
//        毕业证
        String graduationUrl = employeeInfoVo.getGraduationUrl();
        if (!StringUtils.isEmpty(graduationUrl)){
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(2); //0:流水，1：头像，2：毕业证
            imgUrlEntity.setOid(id);
            imgUrlEntity.setName("毕业证");
            imgUrlEntity.setUrl(graduationUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }
//        学位证
        String degreeUrl = employeeInfoVo.getDegreeUrl();
        if (!StringUtils.isEmpty(degreeUrl)){
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(3); //0:流水，1：头像，2：毕业证,3:学位证
            imgUrlEntity.setOid(id);
            imgUrlEntity.setName("学位证");
            imgUrlEntity.setUrl(degreeUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }
//        离职证明
        String dimissionUrl = employeeInfoVo.getDimissionUrl();
        if (!StringUtils.isEmpty(dimissionUrl)){
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(4); //0:流水，1：头像，2：毕业证,3:学位证，4：离职证明
            imgUrlEntity.setOid(id);
            imgUrlEntity.setName("离职证明");
            imgUrlEntity.setUrl(degreeUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }

//        离职报告
        String healthUrl = employeeInfoVo.getHealthUrl();
        if (!StringUtils.isEmpty(healthUrl)){
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(5); //0:流水，1：头像，2：毕业证,3:学位证，4：离职证明,5：体检报告
            imgUrlEntity.setOid(id);
            imgUrlEntity.setName("体检报告");
            imgUrlEntity.setUrl(degreeUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }

        String photoUrl = employeeInfoVo.getPhotoUrl();
        if (!StringUtils.isEmpty(photoUrl)){

            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(0); //0:流水，1：头像
            imgUrlEntity.setOid(id);
            imgUrlEntity.setName("1寸照片");
            imgUrlEntity.setUrl(photoUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }

        List<String> idcardImgs = employeeInfoVo.getIdcardImgs();
        if (!CollectionUtils.isEmpty(idcardImgs)){
            for (String idcardImg : idcardImgs) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setType(6); //0:流水，1：头像
                imgUrlEntity.setOid(id);
                imgUrlEntity.setName("身份证正反面");
                imgUrlEntity.setUrl(idcardImg);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlService.saveE(imgUrlEntity);
            }
        }
        List<String> credential = employeeInfoVo.getCredential(); //证书
        if (!CollectionUtils.isEmpty(credential)){
            for (String s : credential) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setType(10); //0:流水，1：头像
                imgUrlEntity.setOid(id);
                imgUrlEntity.setName("职称证书");
                imgUrlEntity.setUrl(s);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlService.saveE(imgUrlEntity);
            }
        }
        List<String> attachments = employeeInfoVo.getAttachments();
        if (!CollectionUtils.isEmpty(attachments)){
            for (String attachment : attachments) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setType(11); //0:流水，1：头像
                imgUrlEntity.setOid(id);
                imgUrlEntity.setName("其他附件");
                imgUrlEntity.setUrl(attachment);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlService.saveE(imgUrlEntity);
            }
        }

    }



    private void getBpmImg( EmployeeBpmDto employeeBpmDto) {
        Long oid = employeeBpmDto.getOid();
        //        面试评价表
        List<ImgUrlEntity> evaluation = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 13));
        employeeBpmDto.setEvaluation(evaluation);
//背调报告
        List<ImgUrlEntity> backReport = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 14));
        employeeBpmDto.setBackReport(backReport);
//        简历原件
        List<ImgUrlEntity> resume = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 15));
        employeeBpmDto.setResume(resume);
//录用邀约函
        List<ImgUrlEntity> invitationLetter = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 16));
        employeeBpmDto.setInvitationLetter(invitationLetter);

        //岗位薪资测算表
        List<ImgUrlEntity> measure = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 17));
        employeeBpmDto.setMeasure(measure);

        //银行流水/薪资证明
        List<ImgUrlEntity> prove = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 18));
        employeeBpmDto.setProve(prove);

        //其他附件
        List<ImgUrlEntity> otherAtt = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 19));
        employeeBpmDto.setOtherAtt(otherAtt);
    }


    private void setBpmImg(@RequestBody @Valid UpdateEmployeeBpmVo updateEmployeeBpmVo) {
        Long oid = updateEmployeeBpmVo.getOid();
//        面试评价表
        List<String> evaluation = updateEmployeeBpmVo.getEvaluation();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",oid).eq("type",13));
        if (!CollectionUtils.isEmpty(evaluation)){
            for (String s : evaluation) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setType(13);
                imgUrlEntity.setUrl(s);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlDao.insert(imgUrlEntity);
            }
        }
//        背调报告
        List<String> backReport = updateEmployeeBpmVo.getBackReport();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",oid).eq("type",14));
        if (!CollectionUtils.isEmpty(backReport)){
            for (String s : backReport) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setType(14);
                imgUrlEntity.setUrl(s);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlDao.insert(imgUrlEntity);
            }
        }
//简历原件
        List<String> resume = updateEmployeeBpmVo.getResume();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",oid).eq("type",15));
        if (!CollectionUtils.isEmpty(resume)){
            for (String s : resume) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setType(15);
                imgUrlEntity.setUrl(s);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlDao.insert(imgUrlEntity);
            }
        }
//        录用邀约函
        List<String> invitationLetter = updateEmployeeBpmVo.getInvitationLetter();

        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",oid).eq("type",16));
        if (!CollectionUtils.isEmpty(invitationLetter)){
            for (String s : invitationLetter) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setType(16);
                imgUrlEntity.setUrl(s);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlDao.insert(imgUrlEntity);
            }
        }

//        岗位薪资测算表
        List<String> measure = updateEmployeeBpmVo.getMeasure();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",oid).eq("type",17));
        if (!CollectionUtils.isEmpty(measure)){
            for (String s : measure) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setType(17);
                imgUrlEntity.setUrl(s);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlDao.insert(imgUrlEntity);
            }
        }
//        银行流水/薪资证明
        List<String> prove = updateEmployeeBpmVo.getProve();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",oid).eq("type",18));
        if (!CollectionUtils.isEmpty(prove)){
            for (String s : prove) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setType(18);
                imgUrlEntity.setUrl(s);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlDao.insert(imgUrlEntity);
            }
        }
//        其他附件
        List<String> otherAtt = updateEmployeeBpmVo.getOtherAtt();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",oid).eq("type",19));
        if (!CollectionUtils.isEmpty(otherAtt)){
            for (String s : otherAtt) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setType(19);
                imgUrlEntity.setUrl(s);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlDao.insert(imgUrlEntity);
            }
        }
    }


    private void updateImg(@RequestBody EmployeeInfoUpdateVo employeeInfoUpdateVo) {
        Long oid = employeeInfoUpdateVo.getOid();
        //        上传原单位薪资流水
        List<String> oldSalaryRecordUrl = employeeInfoUpdateVo.getOldSalaryRecordUrl();
//        先删除
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",oid).eq("type",1));
        if (!CollectionUtils.isEmpty(oldSalaryRecordUrl)){
            for (String s : oldSalaryRecordUrl) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setName("原公司工资流水");
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setType(1); //0:流水，1：头像
                imgUrlEntity.setCreateTime(new Date());
                imgUrlEntity.setUrl(s);
                imgUrlService.saveE(imgUrlEntity);
            }
        }
//        毕业证
        String graduationUrl = employeeInfoUpdateVo.getGraduationUrl();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",oid).eq("type",2)); //先删除
        if (!StringUtils.isEmpty(graduationUrl)){
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(2); //0:流水，1：头像，2：毕业证
            imgUrlEntity.setOid(oid);
            imgUrlEntity.setName("毕业证");
            imgUrlEntity.setUrl(graduationUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }
//        学位证
        String degreeUrl = employeeInfoUpdateVo.getDegreeUrl();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",oid).eq("type",3)); //先删除
        if (!StringUtils.isEmpty(degreeUrl)){
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(3); //0:流水，1：头像，2：毕业证,3:学位证
            imgUrlEntity.setOid(oid);
            imgUrlEntity.setName("学位证");
            imgUrlEntity.setUrl(degreeUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }
//        离职证明
        String dimissionUrl = employeeInfoUpdateVo.getDimissionUrl();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",oid).eq("type",4)); //先删除
        if (!StringUtils.isEmpty(dimissionUrl)){
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(4); //0:流水，1：头像，2：毕业证,3:学位证，4：离职证明
            imgUrlEntity.setOid(oid);
            imgUrlEntity.setName("离职证明");
            imgUrlEntity.setUrl(degreeUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }

//        体检报告
        String healthUrl = employeeInfoUpdateVo.getHealthUrl();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",oid).eq("type",5)); //先删除
        if (!StringUtils.isEmpty(healthUrl)){
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(5); //0:流水，1：头像，2：毕业证,3:学位证，4：离职证明,5：体检报告
            imgUrlEntity.setOid(oid);
            imgUrlEntity.setName("体检报告");
            imgUrlEntity.setUrl(degreeUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }

//        头像
        String photoUrl = employeeInfoUpdateVo.getPhotoUrl();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",oid).eq("type",0)); //先删除
        if (!StringUtils.isEmpty(photoUrl)){

            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(0); //0:流水，1：头像
            imgUrlEntity.setOid(oid);
            imgUrlEntity.setName("1寸照片");
            imgUrlEntity.setUrl(photoUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }


        List<String> idcardImgs = employeeInfoUpdateVo.getIdcardImgs();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",oid).eq("type",6)); //先删除
        if (!CollectionUtils.isEmpty(idcardImgs)){
            for (String idcardImg : idcardImgs) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setType(6); //0:流水，1：头像
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setName("身份证正反面");
                imgUrlEntity.setUrl(idcardImg);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlService.saveE(imgUrlEntity);
            }
        }
        List<String> credential = employeeInfoUpdateVo.getCredential(); //证书
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",oid).eq("type",10)); //先删除
        if (!CollectionUtils.isEmpty(credential)){
            for (String s : credential) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setType(10); //0:流水，1：头像
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setName("职称证书");
                imgUrlEntity.setUrl(s);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlService.saveE(imgUrlEntity);
            }
        }
        List<String> attachments = employeeInfoUpdateVo.getAttachments();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",oid).eq("type",11)); //先删除
        if (!CollectionUtils.isEmpty(attachments)){
            for (String attachment : attachments) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setType(11); //0:流水，1：头像
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setName("其他附件");
                imgUrlEntity.setUrl(attachment);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlService.saveE(imgUrlEntity);
            }
        }
    }





    /**
     * 根据身份证查询旧员工
     * @param idCard
     * @return
     */

    public OldEmployeeEntity findEmpByIdcard(String idCard){

//        jobDaoMssql.findEmpByIdcard(idCard);
        List<OldEmployeeBo> empByIdcards = new ArrayList<>();
        if (CollectionUtils.isEmpty(empByIdcards)){
            return null;
        }
        OldEmployeeBo empByIdcard = empByIdcards.get(0);
        OldEmployeeEntity oldEmployeeEntity = BeanUtilsMabach.doToDto(empByIdcard, OldEmployeeEntity.class);
        Long professionJoblevelId = empByIdcard.getProfessionJoblevelId();
        Long managementJoblevelId = empByIdcard.getManagementJoblevelId();
        if (managementJoblevelId!=null){
            oldEmployeeEntity.setJobLevelType(2);
            oldEmployeeEntity.setJobLevelId(managementJoblevelId);
        }else {
            oldEmployeeEntity.setJobLevelType(1);
            oldEmployeeEntity.setJobLevelId(professionJoblevelId);
        }




        Date dimissiondate = empByIdcard.getDimissiondate();


        Integer days=null;
        if (dimissiondate!=null){
            days = DateUtils.daysBetween(dimissiondate, new Date());
        }



        oldEmployeeEntity.setDaysBetween(days);
        oldEmployeeEntity.setOldhiredate(oldEmployeeEntity.getHiredate());









        return oldEmployeeEntity;

    }






    private void getImg(Long oid, EmployeeInfoDto employeeInfoDto) {
        //        如果薪资流水不为空，则封装进去
        List<ImgUrlEntity> imgUrlEntities = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 1));
        if (!CollectionUtils.isEmpty(imgUrlEntities)){
            ArrayList<String> recordUrls = new ArrayList<>();
            for (ImgUrlEntity imgUrlEntity : imgUrlEntities) {
                recordUrls.add(imgUrlEntity.getUrl());
            }
            employeeInfoDto.setOldSalaryRecordUrl(recordUrls);
        }
//        封装头像
        ImgUrlEntity imgUrlEntity = imgUrlDao.selectOne(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 0));
        if (!ObjectUtils.isEmpty(imgUrlEntity)){
            employeeInfoDto.setPhotoUrl(imgUrlEntity.getUrl());
        }

        //0:流水，1：头像，2：毕业证,3:学位证，4：离职证明,5：体检报告
        ImgUrlEntity imgUrlEntity2 = imgUrlDao.selectOne(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 2));
        if (!ObjectUtils.isEmpty(imgUrlEntity2)){
            employeeInfoDto.setGraduationUrl(imgUrlEntity2.getUrl());
        }
//        学位证
        ImgUrlEntity imgUrlEntity3 = imgUrlDao.selectOne(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 3));
        if (!ObjectUtils.isEmpty(imgUrlEntity3)){
            employeeInfoDto.setDegreeUrl(imgUrlEntity3.getUrl());
        }
//        离职证明
        ImgUrlEntity imgUrlEntity4 = imgUrlDao.selectOne(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 4));
        if (!ObjectUtils.isEmpty(imgUrlEntity4)){
            employeeInfoDto.setDimissionUrl(imgUrlEntity4.getUrl());
        }
//        体检报告
        ImgUrlEntity imgUrlEntity5 = imgUrlDao.selectOne(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 5));
        if (!ObjectUtils.isEmpty(imgUrlEntity5)){
            employeeInfoDto.setHealthUrl(imgUrlEntity5.getUrl());
        }

        //        身份证
        List<ImgUrlEntity> imgUrlEntityList = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 6));
        ArrayList<String> strings = new ArrayList<>();
        if (!CollectionUtils.isEmpty(imgUrlEntityList)){
            for (ImgUrlEntity urlEntity : imgUrlEntityList) {
                strings.add(urlEntity.getUrl());
            }
            employeeInfoDto.setIdcardImgs(strings);
        }

//职称
        List<ImgUrlEntity> imgUrlEntityList3 = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 10));
        ArrayList<String> strings1 = new ArrayList<>();
        if (!CollectionUtils.isEmpty(imgUrlEntityList3)){
            for (ImgUrlEntity urlEntity : imgUrlEntityList3) {
                strings1.add(urlEntity.getUrl());
            }
            employeeInfoDto.setCredential(strings1);
        }

//        其他附件

        List<ImgUrlEntity> imgUrlEntityList4 = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 11));
        ArrayList<String> strings2 = new ArrayList<>();
        if (!CollectionUtils.isEmpty(imgUrlEntityList4)){
            for (ImgUrlEntity urlEntity : imgUrlEntityList4) {
                strings2.add(urlEntity.getUrl());
            }
            employeeInfoDto.setAttachments(strings2);
        }

    }


    public String getUserCode(){
        Date date = new Date();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String datestr = format.format(date);
        String nm = new SimpleDateFormat("yyyyMMdd").format(date);
        Long max = employeeInfoDao.getEmployeeOidList(datestr)+1;
        String employeeOidStr = String.format("%05d", max);
        return nm+employeeOidStr;
    }

    /**
     * 保存图片
     * @param memberEmpBpmUpdateVo
     * @return
     */
    private void saveImg(@RequestBody @Valid MemberEmpBpmUpdateVo memberEmpBpmUpdateVo) {
        Long id = memberEmpBpmUpdateVo.getOid();
//修改流水
        List<String> oldSalaryRecordUrl = memberEmpBpmUpdateVo.getOldSalaryRecordUrl();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",id).eq("type",1));
        if (!CollectionUtils.isEmpty(oldSalaryRecordUrl)){

            for (String s : oldSalaryRecordUrl) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setName("原公司工资流水");
                imgUrlEntity.setOid(id);
                imgUrlEntity.setType(1);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlEntity.setUrl(s);
                imgUrlService.saveE(imgUrlEntity);

            }
        }
//        照片
        String photoUrl = memberEmpBpmUpdateVo.getPhotoUrl();
        if (!StringUtils.isEmpty(photoUrl)){

            imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",id).eq("type",0));
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(0);
            imgUrlEntity.setOid(id);
            imgUrlEntity.setName("1寸照片");
            imgUrlEntity.setUrl(photoUrl);
            imgUrlEntity.setCreateTime(new Date());

            imgUrlService.saveE(imgUrlEntity);
        }

        //        毕业证
        String graduationUrl = memberEmpBpmUpdateVo.getGraduationUrl();
        if (!StringUtils.isEmpty(graduationUrl)){
            imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",id).eq("type",2));
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(2); //0:流水，1：头像，2：毕业证
            imgUrlEntity.setOid(id);
            imgUrlEntity.setName("毕业证");
            imgUrlEntity.setUrl(graduationUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }
//        学位证
        String degreeUrl = memberEmpBpmUpdateVo.getDegreeUrl();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",id).eq("type",3));
        if (!StringUtils.isEmpty(degreeUrl)){

            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(3); //0:流水，1：头像，2：毕业证,3:学位证
            imgUrlEntity.setOid(id);
            imgUrlEntity.setName("学位证");
            imgUrlEntity.setUrl(degreeUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }
//        离职证明
        String dimissionUrl = memberEmpBpmUpdateVo.getDimissionUrl();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",id).eq("type",4));
        if (!StringUtils.isEmpty(dimissionUrl)){
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(4); //0:流水，1：头像，2：毕业证,3:学位证，4：离职证明
            imgUrlEntity.setOid(id);
            imgUrlEntity.setName("离职证明");
            imgUrlEntity.setUrl(degreeUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }

//        体检报告
        String healthUrl = memberEmpBpmUpdateVo.getHealthUrl();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",id).eq("type",5));
        if (!StringUtils.isEmpty(healthUrl)){
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(5); //0:流水，1：头像，2：毕业证,3:学位证，4：离职证明,5：体检报告
            imgUrlEntity.setOid(id);
            imgUrlEntity.setName("体检报告");
            imgUrlEntity.setUrl(degreeUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }
//        身份证
        List<String> idcardImgs = memberEmpBpmUpdateVo.getIdcardImgs();
        if (!CollectionUtils.isEmpty(idcardImgs)){
            imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid",id).eq("type",6));
            for (String idcardImg : idcardImgs) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setType(6); //0:流水，1：头像，2：毕业证,3:学位证，4：离职证明,5：体检报告,6:身份证正反面
                imgUrlEntity.setOid(id);
                imgUrlEntity.setName("身份证");
                imgUrlEntity.setUrl(idcardImg);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlService.saveE(imgUrlEntity);
            }

        }
//        return id;
    }











    public static void main(String[] args) {

        System.out.println("select \n" +
                "C_OID,\n" +
                "C_CODE,\n" +
                "C_NAME,\n" +
                "C_HIREDATE,\n" +
                "C_ORGNAME,\n" +
                "C_UNITNAME,\n" +
                "C_JOBNAME,\n" +
                "C_EMPLOYEESTATUS,\n" +
                "C_IDCARD,\n" +
                "C_RECORDTIME,\n" +
                "C_HIREINFO,\n" +
                "C_ORGID,\n" +
                "C_UNITID,\n" +
                "C_JOBID,\n" +
                "C_CENTERPEOPLE,\n" +
                "C_PETPEOPLE,\n" +
                "C_MYPHONE,\n" +
                "C_EMAIL\n" +
                "from tb_inf_employee e  with(nolock)\n" +
                "left join (select c_recordtime,C_EMPOID from tb_per_staffrecord with(nolock) where C_RECORDTYPE in (4,6,5,8)) s on s.C_EMPOID = e.C_EMPLOYEEID\n" +
                "where 1=1\n" +
                "and C_IDCARD=");
    }


    /**
     * 是否是负责人
     * @param request
     * @param oid
     * @return
     * @throws Exception
     */
    private boolean isPrincipalUser(HttpServletRequest request,Long oid)throws  Exception{
        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(oid);
        R u = loginController.getUserInfo(request);
        JSONObject user = (JSONObject) u.getData();
        String userCode = user.getString("usercode");
        if(userCode.equals(employeeInfoEntity.getPrincipalUserCode())){
            return true;
        }else{
            return false;
        }
    }


    private void setArgs(EmployeeBpmEntity bpmEntity, EmployeeBpmDto employeeBpmDto) {
        Long orgId = bpmEntity.getOrgId();
        String orgNameById = jobController.getOrgNameById(orgId);
        employeeBpmDto.setOrgname(orgNameById);

//        部门
        Long unitId = bpmEntity.getUnitId();
        String unitname = jobController.getOrgNameById(unitId);
        employeeBpmDto.setUnitname(unitname);
//        职级
        Long jobLevelId = bpmEntity.getJobLevelId();
        String jobLevelNameById = jobController.getJobLevelNameById(jobLevelId);
        employeeBpmDto.setJobLevel(jobLevelNameById);
//        岗位
        Long jobId = bpmEntity.getJobId();
        String jobName = jobController.getJobName(jobId);
        employeeBpmDto.setJobname(jobName);

//        原公司
        Long oldCompanyId = bpmEntity.getOldCompanyId();
        String oldCompany = jobController.getOrgNameById(oldCompanyId);
        employeeBpmDto.setOldCompany(oldCompany);
//        原部门
        Long oldDepId = bpmEntity.getOldDepartmentId();
        String oldDep = jobController.getOrgNameById(oldDepId);
        employeeBpmDto.setOldDepartment(oldDep);
//        原职级
        Long oldJobLevelId = bpmEntity.getOldJobLevelId();
        String oldJobLevel = jobController.getJobLevelNameById(oldJobLevelId);
        employeeBpmDto.setOldJobLevel(oldJobLevel);
//        原岗位
        Long oldJobId = bpmEntity.getOldJobId();
        String oldJobName = jobController.getJobName(oldJobId);
        employeeBpmDto.setOldJobName(oldJobName);
    }





}
